# PowerShell启动脚本，用于运行用户服务并添加必要的JVM参数

Write-Host "========================================="
Write-Host "NS-BBS 用户服务启动脚本"
Write-Host "版本: 1.0.0"
Write-Host "用途: 解决JDK 9+与Dubbo 2.7.x的兼容性问题"
Write-Host "========================================="

# 检测Java版本
Write-Host "检测Java版本..."
java -version

# 设置完整的JVM参数，解决JDK 9+模块化问题
$JAVA_OPTS = "--add-opens java.base/java.lang=ALL-UNNAMED --add-opens java.base/java.io=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED --add-opens java.base/java.lang.reflect=ALL-UNNAMED --add-opens java.base/java.text=ALL-UNNAMED --add-opens java.desktop/java.awt.font=ALL-UNNAMED"

# 设置Dubbo特定系统属性
$SYSTEM_PROPS = "-Ddubbo.application.logger=slf4j -Dsun.misc.Unsafe.allowUnsafeImplementations=true"

Write-Host "正在启动用户服务，使用以下JVM参数:"
Write-Host $JAVA_OPTS
Write-Host $SYSTEM_PROPS

# 进入用户服务目录
Set-Location "d:\Code\Community\springboot\user\bbs-user-service"

# 检查目录是否正确
if (-not (Test-Path "pom.xml")) {
    Write-Host "错误: 找不到pom.xml文件，请检查目录路径是否正确"
    Read-Host "按Enter键退出..."
    exit 1
}

# 清理并打包项目
Write-Host "========================================="
Write-Host "正在构建项目..."
Write-Host "========================================="
mvn clean package -DskipTests

if ($LASTEXITCODE -ne 0) {
    Write-Host "错误: 构建失败，请检查错误信息"
    Read-Host "按Enter键退出..."
    exit $LASTEXITCODE
}

# 检查JAR文件是否生成
if (-not (Test-Path "target\bbs-user-service-3.0.0-SNAPSHOT.jar")) {
    Write-Host "警告: 找不到预期的JAR文件，可能是文件名不同"
    Write-Host "正在查找可用的JAR文件..."
    Get-ChildItem -Path "target\" -Filter "*.jar" | Select-Object -ExpandProperty Name
    Read-Host "按Enter键继续..."
}

# 运行应用
Write-Host "========================================="
Write-Host "正在启动应用..."
Write-Host "如果遇到问题，请考虑降级到JDK 8运行此应用"
Write-Host "========================================="

# 合并所有参数
$all_args = "$JAVA_OPTS $SYSTEM_PROPS -jar target/bbs-user-service-3.0.0-SNAPSHOT.jar"

# 运行Java应用
java $all_args.Split(" ")

# 捕获退出代码
$exit_code = $LASTEXITCODE

Write-Host "========================================="
Write-Host "应用已退出，退出代码: $exit_code"
if ($exit_code -ne 0) {
    Write-Host "错误: 应用启动失败，请查看上述错误信息"
    Write-Host "建议解决方案:"
    Write-Host "1. 确保已安装JDK 8或添加了正确的JVM参数"
    Write-Host "2. 检查Zookeeper服务是否正在运行"
    Write-Host "3. 尝试重新构建项目"
} else {
    Write-Host "应用已成功启动"
}
Read-Host "按Enter键退出..."